package es.us.lsi.daw.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * The Class XMLReader.
 */
public class XMLUtil {

	public static String	DTD_LOCALE	= "<!DOCTYPE root [<!ELEMENT root (static-content*)><!ELEMENT static-content (#PCDATA)><!ATTLIST static-content id ID #REQUIRED>]>";
	public static Logger	log			= LoggerFactory.getLogger(XMLUtil.class);

	/**
	 * Parses the xml file.
	 * 
	 * @param file
	 *            the file
	 * @return the document
	 * @throws ParserConfigurationException
	 *             the parser configuration exception
	 * @throws SAXException
	 *             the sAX exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static Document parseXmlFile(final String file) throws ParserConfigurationException, SAXException, IOException {

		// Document
		Document document = null;
		// get the factory
		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);

		// Using factory get an instance of document builder
		final DocumentBuilder docBuilder = dbf.newDocumentBuilder();

		// parse using builder to get DOM representation of the XML file
		document = docBuilder.parse(new InputSource(file));

		return document;
	}

	/**
	 * Parses the text.
	 * 
	 * @param text
	 *            the text
	 * @return the document
	 * @throws ParserConfigurationException
	 *             the parser configuration exception
	 * @throws SAXException
	 *             the sAX exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static Document parseText(final String text) throws ParserConfigurationException, SAXException, IOException {

		// Document
		Document document = null;
		// get the factory
		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);

		// Using factory get an instance of document builder
		final DocumentBuilder docBuilder = dbf.newDocumentBuilder();

		// parse using builder to get DOM representation of the XML file
		document = docBuilder.parse(new ByteArrayInputStream(text.getBytes()));

		return document;
	}

	public static String parseXMLInternacionalizacion(Map<String, String> traducciones) {

		StringBuffer sb = new StringBuffer();

		// sb.append("<?xml version=\"1.0\"?>");
		sb.append("<root>");
		Set<String> listaClaves = traducciones.keySet();
		for (String clave : listaClaves) {

			sb.append("<static-content id=\"" + clave + "\">");
			sb.append(traducciones.get(clave));
			sb.append("</static-content>");

		}
		sb.append("</root>");

		return sb.toString();
	}

	public static Map<String, String> getLocalizedMap(String xml) {

		Map<String, String> traducciones = new HashMap<String, String>();
		if (xml != null && !xml.isEmpty()) {
			try {
				Document document = XMLUtil.parseText(DTD_LOCALE + xml);

				NodeList element = document.getElementsByTagName("static-content");
				for (int i = 0; i < element.getLength(); i++) {
					String clave = element.item(i).getAttributes().getNamedItem("id").getFirstChild().getNodeValue();

					if (element.item(i).getFirstChild() != null) {
						String valor = element.item(i).getFirstChild().getNodeValue();
						traducciones.put(clave, valor);
					} else {
						traducciones.put(clave, "");
					}
				}
			} catch (Exception e) {
				log.error("XML mal formado: " + xml, e);
			}
		}
		return traducciones;
	}

}
